//
//  IAPManager.swift
//  O Chat
//
//  Created by ivic on 2018/12/26.
//  Copyright © 2018 ivic. All rights reserved.
//

import UIKit
import StoreKit
@objc public protocol applePurchaseDelegate: NSObjectProtocol{
    func getProductsFromApple(_ money: String)
}
class IAPManager: NSObject {
    var appPayDelegate:applePurchaseDelegate?
    fileprivate var productDict:NSMutableDictionary?
    fileprivate let VERIFY_RECEIPT_URL = "https://buy.itunes.apple.com/verifyReceipt"
    fileprivate let ITMS_SANDBOX_VERIFY_RECEIPT_URL = "https://sandbox.itunes.apple.com/verifyReceipt"
    // 单例
    static let shared = IAPManager.init()
    private override init(){}
    var successType:String = "0"
    var coinString:String?
    
    //最好是在AppDelegate里面添加监听,一旦下次近来的时候回自动检测到未完成的内购
    func addTransactionObserver() {
        SKPaymentQueue.default().add(self)
    }
    
    func restoreTransaction() {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

    
    func removeTransactionObserver() {
        SKPaymentQueue.default().remove(self)
    }
    // 点击购买产品后触发的
    func startPaymentWithProductId(productId: String){
    
        print("startPaymentWithProductId")
        Toast_View_Tool.show()
        let productIDArray = [productId]
        let sets = NSSet.init(array: productIDArray)
        let sKProductsRequest = SKProductsRequest.init(productIdentifiers: sets as! Set<String>)
        sKProductsRequest.delegate = self
        sKProductsRequest.start()
        
    }
    
}
                
extension IAPManager:SKPaymentTransactionObserver {
             
    
    func failedTransaction(transaction:SKPaymentTransaction) -> Void {
        SKPaymentQueue.default().finishTransaction(transaction)
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        print("paymentQueuepaymentQueue=-=========       ")

        Toast_View_Tool.show()

        for transaction:SKPaymentTransaction in transactions {
            switch transaction.transactionState {
            case .purchasing:
                //3304 0.99 9.99
                print("正在购买,请稍候...")
                Toast_View_Tool.show()
            case .purchased:
                print("购买成功")
                self.buyAppleStoreProductSucceedWithPaymentTransactionp(paymentTransactionp: transaction)
                
            case .failed:
                Toast_View_Tool.show(type: .error,text: "Pay failure")
                self.failedTransaction(transaction: transaction)
                print(transaction.error)
                print("failedfailedfailed")
                
            case .restored:
                print("恢复购买中")
                Toast_View_Tool.dismiss()
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshChargeNotice"), object: nil, userInfo:nil)
                
            case .deferred:
                Toast_View_Tool.show(type: .error,text: "waiting...")
                print("deferreddeferred")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshChargeNotice"), object: nil, userInfo:nil)
                SKPaymentQueue.default().finishTransaction(transaction)
            }
        }
    }
        
    func buyAppleStoreProductSucceedWithPaymentTransactionp(paymentTransactionp:SKPaymentTransaction) {
        
        
        let url = Bundle.main.appStoreReceiptURL
        let appstoreRequest = URLRequest.init(url: url!)
        do {
            
            let reciptaData = try NSURLConnection.sendSynchronousRequest(appstoreRequest, returning: nil)
            let transactionRecipsting:String = reciptaData.base64EncodedString(options: .endLineWithLineFeed)
            //self.checkAppstorePayResultWithBase64String(transactionRecipsting)
            let str = transactionRecipsting.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            print(str)
            print("IAPManagerIAPManagerIAPManagerIAPManager")
            // 倪匡
            RT.buySuccessWith(code: str, coins: coinString ?? "") { (info) in
                NotificationCenter.default.post(name:rechargeNotice, object: nil, userInfo: nil)
                Toast_View_Tool.show(type: .success,text: "Success!")
                SKPaymentQueue.default().finishTransaction(paymentTransactionp)
            }

        } catch let error as NSError {
            print(error)
            Toast_View_Tool.dismiss()
        }
    }
                
    func checkAppstorePayResultWithBase64String(_ base64String:String) {
                //
    }
                
    @objc func gohiddent(view:UIView){
        //        self.imageView.isHidden = true
        UIApplication.shared.keyWindow?.viewWithTag(1001)?.removeFromSuperview()
    }

                
}
                
extension IAPManager : SKProductsRequestDelegate {
                
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        let products = response.products
        print("productsRequest=-=========       ")
        Toast_View_Tool.show()
        for sKProduct in products {
            print("SKProduct 描述信息:\(sKProduct.description)")
            print("localizedTitle 产品标题:\(sKProduct.localizedTitle)")
            print("localizedDescription 产品描述信息:\(sKProduct.localizedDescription)")
            print("price 价格:\(sKProduct.price)")
            print("productIdentifier Product id:\(sKProduct.productIdentifier)")
            self.buyProduct(product: sKProduct)
        }
    }
                    
    func buyProduct(product:SKProduct) {
        let skpayment = SKPayment(product: product)
        SKPaymentQueue.default().add(skpayment)
    }
                    
}

